<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px" label-position="left">
          <el-col :span="8">
            <el-form-item label="损溢日期" style="height:30px">
            <el-date-picker
              v-model="alarmdate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据编号"><el-input
              v-model="listQuery.fbillno"
              clearable
              class="filter-item"
              placeholder="请输入单据编号"
            /></el-form-item>
          </el-col>
          <template v-if="showAll">
            <el-col :span="8">
              <el-form-item label="单据状态">
                <el-select
              v-model="listQuery.fbillstate"
              class="filter-item"
              clearable
              placeholder="请选择单据状态"
            >
              <el-option
                v-for="item in fbillstateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="仓库名称">
                  <el-select
                  v-model="listQuery.fstockno"
                  class="filter-item"
                  clearable
                  placeholder="请选择仓库名称"
                >
                  <el-option
                    v-for="item in fstocknoOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item class="searchOne" label="盘点人员">
                <el-select style="display: inline-block" clearable filterable v-model="listQuery.fpduser" class="filter-item" placeholder="请选择盘点人员">
                    <el-option
                    v-for="item in getListfpduser"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
                  </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="8">
            <el-form-item>
            <el-button type="primary" @click="handleFilter">查找</el-button>
            <el-button type="success" @click="handleCreate">添加</el-button>
            <el-button type="info" @click="handleUpload">导入</el-button>
            <el-button type="text" icon="el-icon-arrow-down" @click="showAll=true"
                v-if="!showAll">展开</el-button>
              <el-button type="text" icon="el-icon-arrow-up" @click="showAll=false" v-else>
                收起</el-button>
          </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
       <JNPF-table   v-loading="listLoading" :data="list">
      <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column :width="buttonColor.operationTwo" align="center" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="text" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="text" @click="audit(scope.row)">确认</el-button>
        </template>
      </el-table-column>
      <el-table-column :width="buttonColor.line" :index="indexMethod" align="center" label="序号" type="index" />
      <el-table-column :width="buttonColor.billno" align="left" label="单据编号" prop="fbillno" />
      <el-table-column :formatter="formatfstockno" align="left" label="仓库名称" prop="fstockno" />
      <el-table-column :width="buttonColor.user" :formatter="formatfpduser" align="left" label="盘点人员" prop="fpduser" />
      <el-table-column :width="buttonColor.date" :formatter="datetimeFormat" align="left" label="盘点日期" prop="fpddate" />
      <el-table-column width="80" :formatter="formatfbilltype" align="left" label="盘点类型" prop="fbilltype" />
       <el-table-column :width="buttonColor.state" align="left" label="盘点状态" prop="fbillstate" >
         <template slot-scope="scope">
          <span
            :style="{color:buttonColor.itemisconfirmed}"
            v-if="scope.row.fbillstate === 1"
            >{{ scope.row.fbillstate | statusFilter }}</span
          >
          <span :style="{color:buttonColor.itemconfirmed}" v-else-if="scope.row.fbillstate === 2">{{
            scope.row.fbillstate | statusFilter
          }}</span>
          <span :style="{color:buttonColor.iteminvalid}" v-else>{{
            scope.row.fbillstate | statusFilter
          }}</span>
        </template>
      </el-table-column>
    </JNPF-table>
    <paginations
	:total="0"
	:page.sync="listQuery.currentPage"
	:limit.sync="listQuery.pageSize"
	/>
      </div>
    </div>
    <el-dialog  :close-on-click-modal="false" 
    :fullscreen="true"
    :before-close="handleClose" :visible.sync="dialogFormVisible">
      <el-tabs type="border-card">
        <el-tab-pane label="头表" :style="{height:screenHeight-230+'px'}">
          <el-row class="JNPF-common-search-box" :gutter="16">
            <el-form @submit.native.prevent label-width="80px"  ref="dataForm" :rules="rules" :model="dataForm">
              <el-col :span="8">
                <el-form-item  label="单据编号" prop="fbillno">
                  <el-input :disabled="true" v-model="dataForm.fbillno" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item  label="盘点日期" prop="fpddate">
              <el-date-picker
                :disabled="true"
                v-model="dataForm.fpddate"
                type="date"
              />
            </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="单据状态" prop="fbillstate">
              <el-select
                disabled
                v-model="dataForm.fbillstate"
                class="filter-item"
                clearable
              >
                <el-option
                  v-for="item in fbillstateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="盘点类型" prop="fbilltype">
              <el-select
                v-model="dataForm.fbilltype"
                class="filter-item"
                clearable
              >
                <el-option
                  v-for="item in fbilltypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
              label="仓库名称"
              prop="fstockno"
            >
              <el-select
                v-model="dataForm.fstockno"
                filterable
                clearable
                class="filter-item"
                placeholder="请选择仓库名称"
              >
                <el-option
                  v-for="item in fstocknoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
              label="盘点人员"
              prop="fpduser"
            >
            <el-select
                  style="display: inline-block"
                  clearable
                  filterable
                  v-model="dataForm.fpduser"
                  class="filter-item"
                  placeholder="请选择操作人员"
                >
                  <el-option
                    v-for="item in getListfpduser"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
            </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="fexplanation">
              <el-input v-model="dataForm.fexplanation" />
            </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="明细表">
          <JNPF-table
                v-loading="listLoading"
                :data="dataForm.details"
                :height="screenHeight-230"
              >
                <el-table-column :width="buttonColor.line" align="center" label="行号" prop="fline" />
                <el-table-column  align="left" label="物料编号" width="150" prop="fgoodno">
                  <template slot-scope="scope">
                      <el-input 
                        v-model="scope.row.fgoodno" 
                        v-direction="{ x: 0, y: scope.$index,type:3}"
                      >
                      <el-button slot="append" icon="el-icon-search" @click="searchDialogMaterial(scope.$index)"></el-button>
                      </el-input>
                    </template>
                </el-table-column>
                <el-table-column  align="left" label="物料名称" prop="fgoodname" />
                <el-table-column  align="left" label="账面数" width="150" prop="fbalqty">
                  <template slot-scope="scope">
                      <el-input 
                        v-model="scope.row.fbalqty" 
                        v-direction="{ x: 1, y: scope.$index,type:3}"
                      >
                      </el-input>
                    </template>
                </el-table-column>
                <el-table-column  align="left" label="实盘数" width="150" prop="fpdqty">
                  <template slot-scope="scope">
                      <el-input 
                        v-model="scope.row.fpdqty" 
                        v-direction="{ x: 2, y: scope.$index,type:3}"
                      >
                      </el-input>
                    </template>
                </el-table-column>
                <el-table-column  align="left" label="损溢数" width="150" prop="flosqty"><template slot-scope="scope">
                      <el-input 
                        v-model="scope.row.flosqty" 
                        v-direction="{ x: 3, y: scope.$index,type:3}"
                      >
                      </el-input>
                    </template></el-table-column>
                <el-table-column  align="left" label="生产日期" prop="fprocdate" />
                <el-table-column  align="left" label="盘点人员" prop="fpduser" />
                <el-table-column  align="left" label="盘点时间" prop="fpddate">
                  <template slot-scope="scope">{{$moment(scope.row.fpddate).format("YYYY-MM_DD HH:mm:ss")}}</template>
                </el-table-column>
                <el-table-column
                  v-if="!viewFlag"
                  align="center"
                  label="操作"
                  :width="buttonColor.operationTwo"
                  class-name="small-padding"
                >
                  <template slot-scope="scope">
                    <el-button type="text"  @click="handleDelete1(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </JNPF-table>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button  @click="cancel()">取消</el-button>
        <el-button type="primary"  v-if="dialogStatus=='create'" @click="createData">确定</el-button>
        <el-button type="primary"  v-else  @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <userDialog :searchVisibleuse.sync="searchVisibleuse" :fsiteNo.sync="userDialogFsiteNo" :tableColor="tableColor" @userDialog="userDialogValue" />
    <material :materialIdVisible.sync="materialIdVisible" :fsiteNo.sync="materialFsiteNo" :tableColor="tableColor" @materialDialog="materialDialogValue" />
  </div>
</template>
<script>
import { listcheckHead, createcheckHead, updatecheckHead, deletecheckHead } from '@/api/tcCheckHead'
import Pagination from '@/components/Pagination'
import UserDialog from '@/components/UserDialog'
import Material from '@/components/Material'
import moment from 'moment'
import { tableColor,titleColor,exportColor,buttonColor } from '@/filters/index'
import { getListArea, getFbillno,checkBiz, uploadPath2 } from "@/api/area";
import { getToken } from '@/utils/auth';
import { listgoodInfo } from '@/api/goodInfo'
import { listgoodInv } from "@/api/goodInv";
import { getApiUrl } from '@/utils/request'

const statusMap = {
  1: '盘点中',
  2: '已结束',
  8: '已作废'
}

export default {
  name: 'ITcCheckHead',
  components: { Pagination, UserDialog, Material },
  filters: {
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      isAdd1: true,
      panelHeight: 0,
       rowid:0,
       showAll:false,
       screenHeight: document.body.clientHeight,
      exportFbillno: null,
      multipleSelection:[],
      downUrl: null,
      uploadVisible: false,
      uploadPath2,
      listgoodInfo: [],
      buttonColor:buttonColor,
      materialIdVisible: false,
      materialFsiteNo: null,
      userFlag:null,
      searchVisibleuse: false,
      userDialogFsiteNo:null,
      dialogFormVisible1: false,
      dialogStatus1: null,
      detailsTmp: [],
      listTmp: [],

      fbalqtyData: null,
      fpdqtyData: 0,
      flosqtyData: 0,

      dataForm1: {
        fbillno: undefined,
        fline: undefined,
        fgoodno: undefined,
        fgoodname: undefined,
        fbalqty: undefined,
        fpdqty: undefined,
        flosqty: undefined,
        fpduser: undefined,
        fpddate: undefined,
        fprocdate: undefined,
      },
      flineList:[],
      selectList:[],

      fstocknoOptions: [],
      getListfpduser: [],
      list: null,
      total: 0,
      listLoading: true,
      alarmdate: null,
      listQuery: {
        page: 1,
        limit: 20,
        fsiteNo: this.$store.state.user.fsiteNo,
        fpduser: undefined,
        fpddate: undefined,
        ftakedateStart: undefined,
        ftakedateEnd: undefined,
        fstockno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        fbilltype: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        fsiteNo: undefined,
        fpduser: undefined,
        fpddate: undefined,
        fstockno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        fbilltype: 2,
        id: undefined,
        details: []
      },
      tableColor,
      titleColor,
      exportColor,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        fsiteNo: [
          { required: true, message: '客户名称不能为空' },
        ],
        fpduser: [
          { required: true, message: '盘点人员不能为空' },
        ],
        fpddate: [
          { required: true, message: '盘点日期不能为空' },
        ],
        fstockno: [
          { required: true, message: '仓库名称不能为空' },
        ],
        fitemcount: [
          { type: 'number', message: '品项数必须为数字值' },
        ],
        fpiececount: [
          { type: 'number', message: '总件数必须为数字值' },
        ],
        ftotalamt: [],
        fexplanation: [],
        fupddate: [],
        foperator: [],
        fcheckdate: [],
        fcheckuser: [],
        fbillstate: [
          { type: 'number', message: '单据状态必须为数字值' },
        ],
        fbilltype: [
          { type: 'number', message: '盘点类型必须为数字值' },
        ],
      },
       rules1: {
        fline: [
          { required: true, message: '行号不能为空' },
          { type: 'number', message: '行号必须为数字值' },
        ],
        fgoodno: [
          { required: true, message: '物料编号不能为空' },
        ],
        fbalqty: [
          { required: true, message: '账面数不能为空' },
        ],
        fpdqty: [
          { required: true, message: '实盘数不能为空' },
        ],
        flosqty: [
          { required: true, message: '损溢数不能为空' },
        ],
        fpduser: [
          { required: true, message: '盘点人员不能为空' },
        ],
        fpddate: [
          { required: true, message: '盘点日期不能为空' },
        ],
      },
      fbillstateOptions: [
        { value: 1, label: '盘点中' },
        { value: 2, label: '已结束' },
        { value: 8, label: '已作废' },
      ],
      fbilltypeOptions:[
        { value: 1, label: '全盘' },
        { value: 2, label: '抽盘' },
      ]
    }
  },
  created() {
    this.keyCode();
    this.downUrl = getApiUrl() + 'xlsx/3-8仓库盘点.xlsx'
    this.panelHeight = document.documentElement.clientHeight-294
    this.alarmdate = [this.parserDate(moment(new Date().setDate(1)).format('YYYY-MM-DD')), new Date()]
    this.getList()
    // 人员弹出框
      getListArea({flag:13,arg1:this.$store.state.user.fsiteNo})
      .then(response => {
        this.getListfpduser = response.data.data.list
      })
      .catch(() => {
        this.getListfpduser = []
      })
       // 仓库名称
    getListArea({ flag: 30,arg1:this.$store.state.user.fsiteNo })
      .then(response => {
        this.fstocknoOptions = response.data.data.list
      })
      .catch(() => {
        this.fstocknoOptions = []
      })
      // 物料列表
      listgoodInfo({limit:-1,fsiteNo:this.$store.state.user.fsiteNo})
      .then(response => {
        this.listgoodInfo = response.data.data.list
      })
      .catch(() => {
        this.listgoodInfo = []
      })
  },
   watch: {
    fbalqtyData: function(val) {
      this.flosqtyData = val - this.fpdqtyData
    },

    fpdqtyData: function(val) {
      this.flosqtyData = this.fbalqtyData - val
    }

  },
 computed: {
    headers() {
      return {
        'Authorization': getToken()
      }
    }
  },
  methods: {
    //回车
    keyCode() {
      let direction = this.$getDirection();
      let _this=this;
      direction.on("keyup", function (e, val) {
        if (e.keyCode === 13) {
          if(val.y==_this.dataForm.details.length-1)
          {
            _this.addrow(res=>{
               direction.next();
            })
          }
          else
          {
           direction.next();
          }
        }
        if (e.keyCode === 37) {
          direction.previous();
        }
        if (e.keyCode === 38) {
          direction.previousLine();
        }
        if (e.keyCode === 40) {
          direction.nextLine();
        }
        if (e.keyCode == 39) {
          direction.next();
        }
      });
    },
    //添加行
    addrow(callback){
      this.dataForm.details.push({
        fline:this.dataForm.details.length+1,
          fgoodno:"",
          fgoodname:"",
          fbalqty:"",
          fpdqty:"",
          flosqty:"0",
          fprocdate:"",
          fpduser:"",
          fpddate:"",
      })
      setTimeout(()=>{
      callback(200)
      },300)
    },
    // 多选
     handleSelectionChange(val) {
        this.multipleSelection = val;

      },
      // 导入
    uploadFileSuccess: function(response) {
          this.uploadVisible = false
          this.$notify.success({
            title: '导入',
            dangerouslyUseHTMLString:true,
            message: response.data
          })


    },
    handleUpload(){
       if(this.multipleSelection.length == 1){
          this.uploadVisible = true
          this.exportFbillno = this.multipleSelection[0].fbillno
       }else{
         this.$notify.error({
              title: '失败',
              message: '请选择一个盘点单据'
            })
       }
    },
    parserDate(date) {
      var t = Date.parse(date)
      if (!isNaN(t)) {
        return new Date(Date.parse(date.replace(/-/g, '/')))
      }
    },
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD')
    },
    datetimeFormatTime(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    formatDate: function(date) {
      if(typeof(date)==='object'){
         var ym
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      var d = date.getDate()
      if (m < 10) {
        m = '0' + m
      }
      if (d < 10) {
        d = '0' + d
      }
      ym = '' + y + m + d
      return ym
      }else{
        return date
      }
    },
    // 仓库名称
    formatfstockno: function(row, column) {
      if (this.fstocknoOptions.length > 0) {
        for (let i = 0; i < this.fstocknoOptions.length; i++) {
          if (row.fstockno === this.fstocknoOptions[i].value) {
            return this.fstocknoOptions[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 物料名称
    formatfgoodno: function(row, column) {
      if(this.listgoodInfo){
        for (let i = 0; i < this.listgoodInfo.length; i++) {
          if (row.fgoodno == this.listgoodInfo[i].fgoodno) {
            return this.listgoodInfo[i].fgoodname
          }
        }
        return ''
      }else{
        return ''
      }
    },
     // 采购单位
    formatfordunit: function(row, column) {
      if (this.listgoodInfo.length > 0) {
        for (let i = 0; i < this.listgoodInfo.length; i++) {
          if (row.fgoodno === this.listgoodInfo[i].fgoodno) {
            return this.listgoodInfo[i].fordunit
          }
        }
        return ''
      } else {
        return ''
      }
    },

    // 物料弹出框
    searchDialogMaterial(id) {
      this.rowid=id;
      this.materialIdVisible = true
      this.materialFsiteNo = this.dataForm.fsiteNo
    },

    // 物料弹出框
    materialDialogValue(value){
       listgoodInv({
        fmonth: moment().format("YYYYMM"),
        fgoodno: value.data.fgoodno,
        fstockno: this.dataForm.fstockno
        })
        .then((response) => {
          this.fbalqtyData = response.data.data.list[0].fbalqty
          this.dataForm.details[this.rowid].fbalqty=response.data.data.list[0].fbalqty;
        })
        .catch(() => {
          this.fbalqtyData = 0
          this.dataForm.details[this.rowid].fbalqty=0;
        });
        this.dataForm.details[this.rowid].fgoodno=value.data.fgoodno;
        this.dataForm.details[this.rowid].fgoodname=value.data.fgoodname;
        // this.dataForm1.fgoodno = value.data.fgoodno
        // this.dataForm1.fgoodname = value.data.fgoodname

    },
      // 搜索人员弹出框
    searchDialoguse(value) {
      this.userFlag = value
      if(this.userFlag==='add'){
        this.userDialogFsiteNo = this.dataForm.fsiteNo
      }else if(this.userFlag==='addFpduser'){
        this.userDialogFsiteNo = this.dataForm.fsiteNo
      }else{
        this.userDialogFsiteNo = this.listQuery.fsiteNo
      }
      this.searchVisibleuse = true
    },

    // 人员弹出框返回值
    userDialogValue(value){
      if(this.userFlag==='add'){
        this.dataForm.fpduser = value.user.id.toString()
      }else if(this.userFlag==='addFpduser'){
        this.dataForm1.fpduser = value.user.id.toString()
      }else{
        this.listQuery.fpduser = value.user.id.toString()
      }
    },

    // 人员
    formatfpduser: function(row, column) {
      if(this.getListfpduser){
        for (let i = 0; i < this.getListfpduser.length; i++) {
        if (row.fpduser == this.getListfpduser[i].value) {
          return this.getListfpduser[i].label
        }
      }
      return ''
      }else{
      return ''
      }
    },
     // 盘点类型
    formatfbilltype: function(row, column) {
      if(this.fbilltypeOptions){
        for (let i = 0; i < this.fbilltypeOptions.length; i++) {
        if (row.fbilltype == this.fbilltypeOptions[i].value) {
          return this.fbilltypeOptions[i].label
        }
      }
      return ''
      }else{
      return ''
      }
    },
    getList() {
      this.listQuery.ftakedateStart = this.alarmdate == null ? null : this.formatDate(this.alarmdate[0])
      this.listQuery.ftakedateEnd = this.alarmdate == null ? null : this.formatDate(this.alarmdate[1])
      this.listLoading = true
      listcheckHead(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        fsiteNo: undefined,
        fpduser: undefined,
        fpddate: undefined,
        fstockno: undefined,
        fitemcount: undefined,
        fpiececount: undefined,
        ftotalamt: undefined,
        fexplanation: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        fbilltype: undefined,
        id: undefined,
        details: []
      }
    },
    resetForm1(){
       this.dataForm1={
        fbillno: undefined,
        fline: undefined,
        fgoodno: undefined,
        fgoodname: undefined,
        fbalqty: undefined,
        fpdqty: undefined,
        flosqty: undefined,
        fpduser: undefined,
        fpddate: undefined,
        fprocdate: undefined,
      }
    },
    handleCreate() {
      this.resetForm()
      // 单据编号
      getFbillno({ flag: 2029 })
        .then((response) => {
          if (response) {
            this.dataForm.fbillno = response.data.data
            this.dialogFormVisible = true
            this.addrow(res=>{})
          }
        })
        .catch(() => {
          this.dataForm.fbillno = ''
        })
        this.dataForm.fbillstate = 1
        this.dataForm.fbilltype = 2
        this.dataForm.fpddate = new Date()
        if (this.fstocknoOptions.length > 0) {
        this.dataForm.fstockno = this.fstocknoOptions[0].value
      }
        this.dataForm.fsiteNo = this.$store.state.user.fsiteNo;
        this.dataForm.fpduser = this.$store.state.user.id.toString()
      this.dialogStatus = 'create'

      // 子表1
      this.handleUpdate1()
      this.resetForm1();
      this.dataForm1.fline = 1
      this.fbalqtyData = 0
      this.fpdqtyData = 0
      this.flosqtyData = 0
      this.dataForm1.fprocdate=new Date()
      this.dataForm1.fpduser=this.$store.state.user.id.toString()
      this.dataForm1.fpddate=new Date()

    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createcheckHead(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加物料盘点主表成功'
              })
              this.selectList=[]
              this.flineList=[]
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleUpdate(row) {
     var fordata =   JSON.parse(JSON.stringify(row))
      this.dataForm = Object.assign({}, fordata)
      this.dialogStatus = 'update'
      this.addrow(res=>{})
      this.dialogFormVisible = true
      this.detailsTmp = [];
      this.listTmp = row;
      if(row.details.length > 0){
        row.details.forEach((v) => {
          this.detailsTmp.push(v);
          this.selectList.push(v.fgoodno)
          this.flineList.push(v.fline)
        });
        var end = row.details[row.details.length-1]
        this.indexs = end.fline+1;
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })

       // 子表1
      this.handleUpdate1()
      this.resetForm1();
       this.fbalqtyData = 0
      this.fpdqtyData = 0
      this.flosqtyData = 0
      this.dataForm1.fprocdate=new Date()
      this.dataForm1.fpduser=this.$store.state.user.id.toString()
      this.dataForm1.fpddate=new Date()
      if(this.dataForm.details.length > 0){
         // 计算行号
        let len = this.dataForm.details.length - 1
        this.dataForm1.fline = this.dataForm.details[len].fline + 1
      }else{
        this.dataForm1.fline = 1
      }
    },
    audit(row) {
        this.$confirm('是否确定', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.dataForm = Object.assign({}, row)
          checkBiz({ pBillNo: this.dataForm.fbillno ,pBillState:2 ,pBizType: 'i_tc_check_head', pUser:this.$store.state.user.id })
              .then(() => {
                for (const v of this.list) {
                  if (v.fbillno === this.dataForm.fbillno) {
                    this.dataForm.fbillstate = 2
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.dataForm)
                    break
                  }
                }
                this.$notify.success({
                  title: '成功',
                  message: '确认成功'
                })
              })
              .catch((response) => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.data
                })
              })
        }).catch(()=>{})
      },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updatecheckHead(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fbillno === this.dataForm.fbillno) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新物料盘点主表成功'
              })
              this.selectList=[]
              this.flineList=[]
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除物料盘点主表', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletecheckHead(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除物料盘点主表成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      }).catch(()=>{})
    },
     addData() {
      this.$refs['dataForm1'].validate((valid) => {
        this.dataForm1.fbalqty = this.fbalqtyData
        this.dataForm1.fpdqty = this.fpdqtyData
        this.dataForm1.flosqty = this.flosqtyData
          // 判断行号是否重复
           this.dataForm1.fline = this.indexs
       const flinetem = this.flineList.indexOf(this.dataForm1.fline)
       // 判断物料id是否重复
       const tem = this.selectList.indexOf(this.dataForm1.fgoodno)
       if(flinetem<0){
          if(tem<0){
          if (valid) {
          this.dialogFormVisible1 = false
          this.dataForm.details.push(this.dataForm1)
          this.selectList.push(this.dataForm1.fgoodno)
          this.flineList.push(this.dataForm1.fline)
          this.indexs++;
          }
        }else{
          this.$notify.error({
                title: '失败',
                message: '所选物料重复'
              })
          return;
        }
       }else{
         this.$notify.error({
              title: '失败',
              message: '行号重复'
            })
         return;
       }
      })

    },

    cancel() {
      this.indexs = 1;
      this.dialogFormVisible = false
      this.selectList=[]
      this.flineList=[]
      this.list.forEach((v) => {
        if (v.fbillno === this.dataForm.fbillno) {
          this.dataForm = this.listTmp
          this.dataForm.details = this.detailsTmp
          const index = this.list.indexOf(v)
          this.list.splice(index, 1, this.dataForm)
          return
        }
      })
    },

    // 弹窗点击关闭前的回调
      handleClose(){
        this.indexs = 1;
        this.dialogFormVisible = false
        this.selectList=[]
      this.flineList=[]
        this.list.forEach((v) => {
          if (v.fbillno === this.dataForm.fbillno) {
            this.dataForm = this.listTmp
            this.dataForm.details = this.detailsTmp
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, this.dataForm)
            return
          }
        })
      },

      handleUpdate1() {
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });
    },


     // 子表一添加编辑
    handleEdit1(row){
          this.dataForm1 = Object.assign({}, row);
              this.fbalqtyData = row.fbalqty
              this.fpdqtyData = row.fpdqty
              this.flosqtyData = row.flosqty
              this.dataForm1.fordunit = this.formatfordunit(row)
              this.dataForm1.fgoodname = this.formatfgoodno(row)
          // 清除验证
          this.$nextTick(() => {
            this.$refs["dataForm1"].clearValidate();
          });

    },
    // 子表一编辑保存数据
    editData1() {
      this.$refs["dataForm1"].validate((valid) => {
        if (valid) {
          if(this.dataForm.details.length > 0){
            let temp = [...this.dataForm.details]
            let isRepeat= false
            // 子表编辑
             for (const v of this.dataForm.details) {
              if (v.fline === this.dataForm1.fline) {
                const index = this.dataForm.details.indexOf(v);
                this.dataForm1.fbalqty = this.fbalqtyData
                this.dataForm1.fpdqty = this.fpdqtyData
                this.dataForm1.flosqty = this.flosqtyData
                // 判断物料是否重复
                temp.splice(index, 1);
                 for (const vi of temp) {
                   if(vi.fgoodno == this.dataForm1.fgoodno){
                     isRepeat = true
                      this.$notify.error({
                            title: '失败',
                            message: '所选物料重复'
                          })
                      return;
                   }
                 }

                 if(!isRepeat){
                      this.dataForm.details.splice(index, 1, this.dataForm1);
                      this.selectList.splice(index, 1, this.dataForm1.fgoodno);
                    this.isAdd1 = false
                    break;
                 }

              }
            }
            // 子表添加
            if(this.isAdd1){
                  this.dataForm1.fbalqty = this.fbalqtyData
                  this.dataForm1.fpdqty = this.fpdqtyData
                  this.dataForm1.flosqty = this.flosqtyData
                    // 判断行号是否重复
                  const flinetem = this.flineList.indexOf(this.dataForm1.fline)
                  // 判断物料id是否重复
                  const tem = this.selectList.indexOf(this.dataForm1.fgoodno)
                  if(flinetem<0){
                      if(tem<0){
                      if (valid) {
                      this.dataForm.details.push(this.dataForm1)
                      this.selectList.push(this.dataForm1.fgoodno)
                      this.flineList.push(this.dataForm1.fline)
                      }
                    }else{
                      this.$notify.error({
                            title: '失败',
                            message: '所选物料重复'
                          })
                      return;
                    }
                  }else{
                    this.$notify.error({
                          title: '失败',
                          message: '行号重复'
                        })
                    return;
                  }
            }
          }else{
                  // 子表第一次添加
                    this.dataForm1.fbalqty = this.fbalqtyData
                    this.dataForm1.fpdqty = this.fpdqtyData
                    this.dataForm1.flosqty = this.flosqtyData
                    // 判断行号是否重复
                  const flinetem = this.flineList.indexOf(this.dataForm1.fline)
                  // 判断物料id是否重复
                  const tem = this.selectList.indexOf(this.dataForm1.fgoodno)
                  if(flinetem<0){
                      if(tem<0){
                      if (valid) {
                      this.dataForm.details.push(this.dataForm1)
                      this.selectList.push(this.dataForm1.fgoodno)
                      this.flineList.push(this.dataForm1.fline)
                      }
                    }else{
                      this.$notify.error({
                            title: '失败',
                            message: '所选物料重复'
                          })
                      return;
                    }
                  }else{
                    this.$notify.error({
                          title: '失败',
                          message: '行号重复'
                        })
                    return;
                  }
          }
            this.resetForm1()
            this.isAdd1 = true
            // 清除验证
            this.$nextTick(() => {
              this.$refs["dataForm1"].clearValidate();
            });
            // 计算行号
             if(this.dataForm.details.length > 0){
              // 计算行号
              let len = this.dataForm.details.length - 1
              this.dataForm1.fline = this.dataForm.details[len].fline + 1
            }else{
              this.dataForm1.fline = 1
            }
            this.fbalqtyData = 0
            this.fpdqtyData = 0
            this.flosqtyData = 0
            this.dataForm1.fprocdate=new Date()
            this.dataForm1.fpduser=this.$store.state.user.id.toString()
            this.dataForm1.fpddate=new Date()
        }
      });
    },

    cancle1(){
         this.resetForm1()
         this.isAdd1 = true

          // 清除验证
          this.$nextTick(() => {
            this.$refs["dataForm1"].clearValidate();
          });

        // 计算行号
        if(this.dataForm.details.length > 0){
          // 计算行号
          let len = this.dataForm.details.length - 1
          this.dataForm1.fline = this.dataForm.details[len].fline + 1
        }else{
          this.dataForm1.fline = 1
        }
        this.fbalqtyData = 0
        this.fpdqtyData = 0
        this.flosqtyData = 0
        this.dataForm1.fprocdate=new Date()
        this.dataForm1.fpduser=this.$store.state.user.id.toString()
        this.dataForm1.fpddate=new Date()
    },


     handleDelete1(row) {
      const index = this.dataForm.details.indexOf(row);
      this.dataForm.details.splice(index, 1);
      this.selectList.splice(index,1)
      this.flineList.splice(index,1)

      this.resetForm1()
       if(this.dataForm.details.length > 0){
         // 计算行号
        let len = this.dataForm.details.length - 1
        this.dataForm1.fline = this.dataForm.details[len].fline + 1
      }else{
        this.dataForm1.fline = 1
      }
      this.fbalqtyData = 0
      this.fpdqtyData = 0
      this.flosqtyData = 0
      this.dataForm1.fprocdate=new Date()
      this.dataForm1.fpduser=this.$store.state.user.id.toString()
      this.dataForm1.fpddate=new Date()
    },

    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>